<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ApiController
 *
 * @author Rakesh Srivastava
 */
Yii::import('application.extensions.Api._base.ECOMAuthenticate');
Yii::import('application.extensions.Api._base.ECOMApiResponder');
Yii::import('application.extensions.Api._base.ECOMResult');

class ApiController extends Controller {

    public $layout = NULL;
    static $postFix = 'ApiFunctionality';
    static $format = 'json';

    private static function requestHandler() {
    	
    	
    	$functionality = $_GET['functionality'];
        $class = $functionality . self::$postFix;
        try {
            $functionalityFile = Yii::app()->getBasePath() . '/extensions/Api/' . $class . '.php';
            if (!file_exists($functionalityFile)) {
                self::functionalityClassNotImplemented($class);
            } else {
                Yii::import('application.extensions.Api.' . $class);
                if (!class_exists($class, true)) {
                    self::functionalityNotImplemented($class);
                } else {
                    $functionalityClassObject = new $class;
                    $action = $_GET['action'];

                    if (!method_exists($functionalityClassObject, $action)) {
                        self::actionNotImplemented($class, $action);
                    } else {
                        $functionalityClassObject->$action();
                    }
                }
            }
        } catch (Exception $e) {
            throw $e;
        }
    }

    // Request Handling here.........
    public function actionList() {
        //Here we add ob_start for start output buffring. Beacuse the output start before the view. 
        ob_start("ob_gzhandler");
        self::requestHandler();
        ob_flush();
    }

    public function actionCreate() {
        //Here we add ob_start for start output buffring. Beacuse the output start before the view. 
        ob_start("ob_gzhandler");
        self::requestHandler();
       ob_flush();
    }

    protected static function functionalityClassNotImplemented($file) {
        $path = Yii::app()->getBasePath() . '/extensions/Api';
        $data = new ECOMResult(501, "Functionality file " . $file . " is not exist in " . $path);
        ECOMApiResponder::Respond($data, date('m-d-Y'), self::$format);
    }

    protected static function functionalityNotImplemented($class) {
        $data = new ECOMResult(501, "Functionality class " . $class . " is not define");
        ECOMApiResponder::Respond($data, date('m-d-Y'), self::$format);
    }

    protected static function actionNotImplemented($class, $action) {
        $data = new ECOMResult(501, "Function $action is not define in $class:");
        ECOMApiResponder::Respond($data, date('m-d-Y'), self::$format);
    }

}

?>